package controller

import (
	"user-go/entity"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sorm"

	"github.com/gin-gonic/gin"
)

func init() {
	sgin.AddRouter(SysRoleMenuController{})
}

type SysRoleMenuController struct {
}

// 查询
// @Router [get] [/sysrolemenu/:id]
func (SysRoleMenuController) Get(c *gin.Context) any {
	id := c.Param("id")
	data := new(entity.SysRoleMenu)
	data.Id = id
	err := sorm.DB.GetOne(data)
	if err != nil {
		return model.NewFailDefault("获取对象失败")
	}
	return data
}

// 增加
// @Router [post] [/sysrolemenu]
func (SysRoleMenuController) Post(c *gin.Context, in *entity.SysRoleMenu) any {
	in.Id = ""
	sorm.DB.Insert(in)
	return model.NewOK(nil)
}

// 修改
// @Router [put] [/sysrolemenu/edit]
func (SysRoleMenuController) Put(c *gin.Context, in *entity.SysRoleMenu) any {
	sorm.DB.UpdateById(in)
	return model.NewOK(nil)
}

// 删除
// @Router [delete] [/sysrolemenu/:id]
func (SysRoleMenuController) Delete(c *gin.Context) any {
	id := c.Param("id")
	sorm.DB.Delete(entity.SysRoleMenu{Id: id})
	return model.NewOK(nil)
}

type RoleMenuVO struct {
	Id       string `json:"id" db:"id,primary_key"`
	RoleId   string `json:"roleId" db:"role_id"`
	MenuId   string `json:"menuId" db:"menu_id"`
	Name     string `json:"name"`
	Title    string `json:"title"`
	ButtonId string `json:"buttonId" db:"button_ids"`
	BtnId    string `json:"btnId" db:"btn_id"`
}

type SysRoleMenuQuery struct {
	Page      model.PageInfo     `json:"page"`
	QueryData entity.SysRoleMenu `json:"queryData"`
}

// 查询列表
// @Router [post] [/sysrolemenu/page]
func (SysRoleMenuController) QueryTables(c *gin.Context, in *SysRoleMenuQuery) any {
	sql := `select a.*, IFNULL(b.name, '') as name, IFNULL(c.title, '') as title, IFNULL(c.btn_id, '') as btn_id from sys_role_menu a left join sys_roles b on a.role_id = b.id
		left join sys_menus c on a.menu_id = c.id where 1=1 and a.button_ids <> '' and a.button_ids is not null`
	data := make([]RoleMenuVO, 0)
	b := sbuilder.Builder(sql)
	sql, values := b.Build()
	return sorm.DB.SelectPage(&data, in.Page, sql, values...)
}
